import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {RegisterPage} from '../register/register';
import {Helper} from "../../common/Helper";
import {ControlsCheck} from "../../common/controlsCheck";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {LoginProvider} from "../../providers/login/login";
import {CONST} from "../../common/const";

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  private form: FormGroup
  private canSub: boolean = true
  private registerPage:any
  private phone:string = ''

  constructor(public navCtrl: NavController,
              private cc: ControlsCheck,
              private fb: FormBuilder,
              private loginProvider: LoginProvider,
              public helper: Helper) {
    this.registerPage = RegisterPage
    this.createForm()
  }

  createForm() {
    this.form = this.fb.group({
      cellphone: ['', Validators.compose([Validators.required, Validators.pattern(CONST.REG_PHONE)])],
      signPassword: ['', Validators.compose([Validators.required, Validators.pattern(CONST.REG_PASSWORD)])],
    })
  }


  setPhoneFromStorage() {
    this.helper.getStorage('user/phone').then((data) => {
      if (data && this.phone == '') {
        this.phone = data
      }
    }).catch(err => {

    })
  }

  submit() {
    if (this.form.valid) {
      if (this.canSub) {
        this.canSub = false
        this.loginProvider.login({
          data: this.form.value,
          complete: ()=>{
            this.canSub = true
          },
          success: ()=>{
            this.navCtrl.pop()
          }
        })
      }
      else return false
    } else {
      this.cc.check(this.form.controls, {
        cellphone: '请输入正确的手机号',
        signPassword: '请输入正确的密码',
      })
    }
  }

  ionViewWillEnter() {
    Helper.setStatusBarTranslucence()
    this.setPhoneFromStorage()
  }

}
